package com.wms.interceptor;

import com.wms.entity.RequestLog;
import com.wms.plugin.JwtPlugin;
import com.wms.security.filter.UrlFilter;
import com.wms.service.RequestLogService;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.CredentialsExpiredException;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.InetAddress;

@Component
public class RequestInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    private JwtPlugin jwtPlugin;

    @Autowired
    private RequestLogService requestLogService;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String ip = getIpAddr(request);
        String url = request.getServletPath();

        RequestLog requestLog = new RequestLog();
        requestLog.setIp(ip);
        requestLog.setUrl(url);

        Claims claims = UrlFilter.getClaims(request, jwtPlugin);
        if (claims != null){
            requestLog.setOperator(claims.get("jti").toString());
        }

        requestLogService.save(requestLog);
        return true;
    }


    private String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
            if(ip.equals("127.0.0.1")){
                //根据网卡取本机配置的IP
                InetAddress inet=null;
                try {
                    inet = InetAddress.getLocalHost();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                ip= inet.getHostAddress();
            }
        }
        // 多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
        if(ip != null && ip.length() > 15){
            if(ip.indexOf(",")>0){
                ip = ip.substring(0,ip.indexOf(","));
            }
        }
        return ip;
    }

}
